package models

import (
	"fmt"
	"github.com/astaxie/goredis"
)

const URL_QUEUR = "url_queue"
const URL_VISIT_SET = "url_visit_set"

var (
	client goredis.Client
)

func ConnRedis(addr string) {
	client.Addr = addr
}

func PutinQueue(url string) {
	_ = client.Lpush(URL_QUEUR, []byte(url))
}

func PopFromQueue() string {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("ERROR : ", err)
		}
	}()
	res, err := client.Rpop(URL_QUEUR)
	if err != nil {
		panic(err)
	}
	return string(res)
}

func GetQueueLength() int {
	length, err := client.Llen(URL_QUEUR)
	if err != nil {
		return 0
	}
	return length
}

func AddToSet(url string) {
	_, _ = client.Sadd(URL_VISIT_SET, []byte(url))
}

func IsVisit(url string) bool {
	bIsVisit, err := client.Sismember(URL_VISIT_SET, []byte(url))
	if err != nil {
		return false
	}
	return bIsVisit
}